package com.defysoft.waukids.attend;

import org.json.JSONObject;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Message;
import android.support.v7.widget.Toolbar;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.defysoft.waukids.BaseActivity;
import com.defysoft.waukids.Data_Type.BC_ATTEND;
import com.defysoft.waukids.JsonParser;
import com.defysoft.waukids.PublicConstant;
import com.defysoft.waukids.R;

public class Attend_Detail_A extends BaseActivity {

	String stu_code = null;
	String stu_name = null;

	String photo;
	String date;
	Toolbar toolbar;
	TextView tv[] = new TextView[2];
	final int FAIR_GETDATE = 9;
	final int SUCCESS_GETDATE = 10;
	BC_ATTEND attend = null;
	private SharedPreferences member;
	ImageView iv;
	WebView wv;
	Spinner spinner;
	String[] celebrities = new String[1];

	@Override
	protected void onActivityResult(int arg0, int arg1, Intent arg2) {
		super.onActivityResult(arg0, arg1, arg2);
		if (arg1 == ATTEND_SELECTDAY_DETAIL_UPDATE_INSERT) {
			setStartData();
			setResult(ATTEND_SELECTDAY_DETAIL_UPDATE_INSERT);
		}
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_attend__detail_);
		setStartData();
	}

	@Override
	public void setStartData() {
		super.setStartData();
		member = getSharedPreferences("member", MODE_PRIVATE);
		stu_code = getIntent().getStringExtra(INTENT_EXTRA_ATTEND_PK_STU_CODE);
		stu_name = getIntent().getStringExtra(INTENT_EXTRA_ATTEND_STU_NAME);
		wv=(WebView)findViewById(R.id.ATTENDDETAIL_IMG);
		wv.setOnTouchListener(new OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				switch (event.getAction()) {
				case MotionEvent.ACTION_DOWN:
					startActivity( new Intent(Attend_Detail_A.this, Attend_SelectDay_Photo_A.class)
					.putExtra("photo",PublicConstant.URI_STUDENDPHOTO+photo));
					break;
				}
				return false;
			}
		});
		date = getIntent().getStringExtra(INTENT_EXTRA_ATTEND_DATE);
		tv[0] = (TextView) findViewById(R.id.ATTENDDETAIL_NAME);
		tv[1] = (TextView) findViewById(R.id.ATTENDDETAIL_ATTTV);
		tv[0].setText(stu_name + "의 출석부\n" + date);
		iv = (ImageView) findViewById(R.id.ATTENDDETAIL_ATTIMG);
		/*iv.setImageResource(R.drawable.attend_detail_at);*/
		spinner = (Spinner) findViewById(R.id.ATTENDDETAIL_SPI);
		toolbar = (Toolbar) findViewById(R.id.ATTENDDETAIL_TOOL);
		toolbar.setNavigationOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		
		startNetwork(1);
	}

	@Override
	public void startThread(int choice) {
		super.startThread(choice);
		if (firstThread != null) {
			firstThread.interrupt();
		}
		firstThread = new Thread(new Runnable() {
			@Override
			public void run() {
				mainThread();
			}
		});
		firstThread.start();
		startDIal();
	}

	@Override
	protected void handlingMessage(Message _message) {
		super.handlingMessage(_message);
		switch (_message.what) {
		case CATCH_EXCEPTION: // 0번은 꼭 try catch의 오류수정코드
			endDIal();
			if (firstThread != null) {
				firstThread.interrupt();
			}
			showPopup("네트워크오류", "네트워크 실패", 0);
			Toast.makeText(this, (String) _message.obj, Toast.LENGTH_LONG)
					.show();
			break;
		case FAIR_GETDATE: // 1번은 꼭 서버에러코드 출력으로
			endDIal();
			if (firstThread != null) {
				firstThread.interrupt();
			}
			showPopup("데이터 갱신실패", (String) _message.obj, 0);
			break;

		case SUCCESS_GETDATE:
			endDIal();
			if (firstThread != null) {
				firstThread.interrupt();
			}
			if (attend != null) {

				iv.setLayoutParams(new LinearLayout.LayoutParams(
						iv.getHeight(), iv.getHeight()));
				if (attend.Att_Check == 0) {
					iv.setImageResource(R.drawable.ch_on);
					tv[1].setText("");
				} else {
					iv.setImageResource(R.drawable.ch_off);
					tv[1].setText(attend.Att_Reason);
				}
				celebrities[0] = "수정";
			} else {
				tv[1].setText("출결사항이 없습니다.");
				celebrities[0] = "입력";
				if (!member.getString("Mem_Rank", "").equals("3")) {
					iv.setImageResource(R.drawable.attend_detail_at);
				}
			}
			if (!member.getString("Mem_Rank", "").equals("3")) {
				setStartToolbar();
				spinner.setVisibility(View.INVISIBLE);
			}
			wv.setVerticalScrollBarEnabled(false);
			wv.setVerticalScrollbarOverlay(false);
			wv.setHorizontalScrollBarEnabled(false);
			wv.setHorizontalScrollbarOverlay(false);
			wv.setInitialScale(100);

			if ( photo == null||photo.length()<5) {// 이미지 파일이 없으면 앱내에서 지정된 이미지를 뿌려주고
				wv.setBackgroundColor(0);
				wv.setBackgroundResource(R.drawable.perm_group_personal_info);
			} else {// 이미지 파일이 있으면
				wv.loadDataWithBaseURL(null,
						creHtmlBody(PublicConstant.URI_STUDENDPHOTO
								+ photo), "text/html", "utf-8", null);
			}
			break;
		}
	}

	protected void mainThread() {
		String msg = "";
		try {
			JSONObject jsonObject = new JSONObject(publicHttpCallback(
					HTTP_SELECT_ATTEND_MONTHDATE, "stu_code=" + stu_code
							+ "&date=" + date));
			if (jsonObject.getBoolean("success")) {
				photo=jsonObject.getString("photo");
				msg = jsonObject.getString("payload");
				if (!msg.equals("false")) {
					attend = JsonParser.AttendSelectFetch(msg);
				} else {
					attend = null;
				}
				onNetworkCallback(SUCCESS_GETDATE, "");
			} else {
				onNetworkCallback(FAIR_GETDATE, jsonObject.getString("message"));
			}
		} catch (Exception e) {
			onNetworkCallback(CATCH_EXCEPTION, e.toString());
		}
		;
	}

	private void setStartToolbar() {
		spinner.setAdapter(new ArrayAdapter<String>(this, 0) {
			@Override
			public int getCount() {
				return celebrities.length;
			}

			@Override
			public View getDropDownView(int position, View convertView,
					ViewGroup parent) {
				final int pos = position;
				if (convertView == null) {
					convertView = getLayoutInflater().inflate(
							R.layout.overflowitem_row, null);
				}
				((TextView) convertView.findViewById(R.id.OVERFLOWITEM_TV))
						.setText(celebrities[position]);
				convertView.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						Intent intent = new Intent(Attend_Detail_A.this,
								Attend_Update_Insert_A.class);
						intent.putExtra(
								PublicConstant.INTENT_EXTRA_ATTEND_PK_STU_CODE,
								stu_code + "");
						intent.putExtra(
								PublicConstant.INTENT_EXTRA_ATTEND_STU_NAME,
								stu_name + "");
						intent.putExtra(INTENT_EXTRA_ATTEND_DATE, date);
						intent.putExtra("photo", PublicConstant.URI_STUDENDPHOTO + photo);
						if (attend != null) {
							intent.putExtra(PublicConstant.INTENT_EXTRA_ATTEND_ATT_REASON,
									attend.Att_Reason + "");
							intent.putExtra(PublicConstant.INTENT_EXTRA_ATTEND_ATT_CHECK,
									attend.Att_Check + "");
							intent.putExtra("photo", PublicConstant.URI_STUDENDPHOTO + photo);
						}
						startActivityForResult(intent, 0);
					}
				});
				return convertView;
			}

			@Override
			public View getView(int position, View convertView, ViewGroup parent) {
				final int pos = position;
				if (convertView == null) {
					convertView = getLayoutInflater().inflate(
							R.layout.overflowitem_row, null);
				}
				((TextView) convertView.findViewById(R.id.OVERFLOWITEM_TV))
						.setBackgroundColor(0x00ffffff);
				return convertView;
			}
		});
		iv.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(Attend_Detail_A.this,
						Attend_Update_Insert_A.class);
				intent.putExtra(
						PublicConstant.INTENT_EXTRA_ATTEND_PK_STU_CODE,
						stu_code + "");
				intent.putExtra(
						PublicConstant.INTENT_EXTRA_ATTEND_STU_NAME,
						stu_name + "");
				intent.putExtra(INTENT_EXTRA_ATTEND_DATE, date);
				intent.putExtra("photo", PublicConstant.URI_STUDENDPHOTO + photo);
				if (attend != null) {
					intent.putExtra(
							PublicConstant.INTENT_EXTRA_ATTEND_ATT_REASON,
							attend.Att_Reason + "");
					intent.putExtra(
							PublicConstant.INTENT_EXTRA_ATTEND_ATT_CHECK,
							attend.Att_Check + "");
					intent.putExtra("photo", PublicConstant.URI_STUDENDPHOTO + photo);
				}
				startActivityForResult(intent, 0);
			}
		});
	}

	public String creHtmlBody(String imagUrl) {
		StringBuffer sb = new StringBuffer("<HTML>");
		sb.append("<HEAD>");
		sb.append("</HEAD>");
		sb.append("<BODY  style='margin: 0; padding: 0'>");
		sb.append("<img width=\"100%\" height=\"100%\" src=\"" + imagUrl
				+ "\">");
		sb.append("</BODY>");
		sb.append("</HTML>");

		return sb.toString();
	}
}
